package domain.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.StringTokenizer;
import java.util.regex.Pattern;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.jsr107cache.Cache;
import net.sf.jsr107cache.CacheException;
import net.sf.jsr107cache.CacheManager;

import domain.data.QnAPersistenceManager;
import domain.model.TrackIp;
import domain.service.GetTrackIp;


@SuppressWarnings("serial")
public class SearchTrackIpServlet extends HttpServlet {
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		resp.setContentType("text/plain");
		resp.setCharacterEncoding("utf-8");
		String ip = req.getRemoteAddr();

        req.setAttribute("ip", ip);		
		String domainName = req.getParameter("name").replaceAll("[^0-9.]+", "");
		String update = req.getParameter("update");
		if(domainName!=null&&domainName.length()>0&&Pattern.matches("^([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +"([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +"([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +"([01]?\\d\\d?|2[0-4]\\d|25[0-5])$", domainName))
		{
			PersistenceManager psm = QnAPersistenceManager.get().getPersistenceManager();
			
			
			@SuppressWarnings("unchecked")
			List<TrackIp> listWhois=  (List<TrackIp>)psm.newQuery(TrackIp.class,"ip == '"+domainName+"'").execute();
			if(listWhois.size()>0)
			{
				Cache cache=null;

		        try {
		            cache = CacheManager.getInstance().getCacheFactory().createCache(Collections.emptyMap());
		        } catch (CacheException e) {
		           e.printStackTrace();
		           
		        }
		        if(cache.containsKey("lastPingIp"))
		        {
		        	@SuppressWarnings("unchecked")
					ArrayList<String> lastPing = (ArrayList<String>)cache.get("lastPingIp");
		        	if(lastPing.size()>19)
		        	{
		        		lastPing.remove(0);
		        		
		        		
		        	}
		        	if(!lastPing.contains(listWhois.get(0).getIp()))
		        	lastPing.add(listWhois.get(0).getIp());
		        	cache.put("lastPingIp", lastPing);
		        	
		        }
		        else
		        {
		        	
		        	ArrayList<String> lastPing = new ArrayList<String>();
		        	if(!lastPing.contains(listWhois.get(0).getIp()))
		        	lastPing.add(listWhois.get(0).getIp());
		        	cache.put("lastPingIp", lastPing);
		        }
				
				
				if(listWhois.get(0).getJsp() == null && listWhois.get(0).getProxy() == null && update == null)
				{
					new GetTrackIp(domainName);
					resp.sendRedirect("/ip/"+domainName+"?update=true");
				}
				req.setAttribute("ip", listWhois);

				@SuppressWarnings("unchecked")
				List<TrackIp> sameip=  (List<TrackIp>)psm.newQuery(TrackIp.class,"ip == '"+listWhois.get(0).getIp()+"'").execute();
				if(sameip.size() > 0)
				{
					req.setAttribute("sameip", sameip.get(0).getDomainString());
				}
				
				String character = listWhois.get(0).getIp().replaceAll("[.]+[0-9]+[.]+[0-9]+$", "");
				Query query = psm.newQuery(TrackIp.class);
				query.setFilter("ip >= :1 && ip < :2");
				query.setRange(0,7);
				@SuppressWarnings("unchecked")
				List<TrackIp> ipList=  (List<TrackIp>)query.execute(character, (character + "\ufffd"));
				req.setAttribute("ipList", ipList);
				
				req.setAttribute("title", "Lookup Ip "+domainName+" - domain-infomation.appspot.com");
				req.setAttribute("description", "Ip "+domainName+".domain-infomation.appspot.com - search, ip lookup information on domain-infomation.appspot.com");
				req.setAttribute("keyword", "ip,ip address,lookup ip,"+domainName);
				
				try {
					req.getRequestDispatcher("/track_ip.jsp").forward(req, resp);
				} catch (ServletException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			} else {
				
				if(update == null)
				{
					TrackIp track = new TrackIp();
					track.setIp(domainName);
					psm.makePersistent(track);
					new GetTrackIp(domainName);
					resp.sendRedirect("/ip/"+domainName+"?update=true");
				} else {
					resp.getWriter().println(domainName+" does not exit !!");
				}
			}
		} else {
			resp.getWriter().println(domainName+" does not exit !!");
		}
		
		
	}
}
